import { Button, Form, Input, InputNumber, Spin, message } from "antd"
import BasicInfo from './BasicInfo'
import { useEffect, useState } from "react"
import GoodsSkuInfo from "./SkuInfo"
import Inventory from './Inventory'
import { Card } from "@/components/Card"
import Logistics from './Logistics'
import { GoodsType, LogisticsType } from "@/constants/enums/goods"
import { useModel } from '@umijs/max'
import { useRequest } from "ahooks"
import { saveGoods, saveGoodsSku, queyGoodsDetail } from "@/services/goods"

const getSkuName = (skus: string, goodsSkus: Goods.Sku[]) => {
  const skuNameList: string[] = []
  const skuList = skus.split('-')
  for (let i=0; i<skuList.length; i++) {
    const sku = skuList[i]
    for (let j=0; i<goodsSkus.length; j++) {
      const good = goodsSkus[j]
      const target = good.skuValue?.find(item => item.valueId === sku)
      if (target) {
        skuNameList.push(target.valueName)
        break
      }
    }
  }
  return skuNameList.join('-')
}

const GoodsAdd: React.FC<RoutePageProps> = (props) => {
  const [basicInfoForm] = Form.useForm()
  const { closeCurrentTab } = useModel('global')
  const { skuList, setSkuList, goodsStock, setGoodsStock } = useModel('mall.physical.goods.goods')
  const saveReq = useRequest(saveGoods, {manual: true})
  const saveSkuReq = useRequest(saveGoodsSku, {manual: true})
  const [saveLoading, setSaveLoading] = useState(false)
  const goodsDetail = useRequest(queyGoodsDetail, {manual: true})

  const cancel = () => {
    closeCurrentTab()
  }
  const saveSku = async () => {
    if (skuList.length < 1) {
      message.error('请添加商品规格')
      return Promise.reject()
    }
    let errMsg: string = ''
    const _nameMap: Record<string, boolean> = {}
    for (let i=0; i<skuList.length; i++) {
      if (!skuList[i].className) {
        errMsg = '请输入规格名称'
        break
      }
      if (skuList[i].values.length < 1) {
        errMsg = '请添加规格值'
        break
      }
      if (i === 0 && skuList[i]._img) {
        if (skuList[i].values.some(it => !it.valueDesc)) {
          errMsg = '请上传规格图片'
          break
        }
      }
      if (_nameMap[skuList[i].className]) {
        errMsg = `存在重复的规格名称：${skuList[i].className}`
        break
      } else {
        _nameMap[skuList[i].className] = true
      }
      if (i > 0 || !skuList[i]._img) {
        skuList[i].values.forEach(it => it.valueDesc = '')
      }
    }
    if (errMsg) {
      message.error(errMsg)
      return Promise.reject()
    }
    return saveSkuReq.runAsync({sku: skuList})
  }
  const submit = () => {
    setSaveLoading(true)
    // if (skuList.length < 1) {
    //
    //   // 需要先保存规格信息
    //   Promise.resolve()
    //     .then(() => {  // 用保存后获取到的真实 sku 替换 fakeId
    //       return Promise.resolve()
    //     })
    //     .then(() => basicInfoForm.validateFields())
    //     .then((values: any) => {
    //       if (goodsStock.length < 1) {
    //         if (!values.goodsPrice) {
    //           message.error('请填写价格')
    //           return Promise.reject()
    //         }
    //         if (!values.goodsNum) {
    //           message.error('请填写库存')
    //           return Promise.reject()
    //         }
    //       }
    //       let minPrice: number = 1000000
    //       let inventory: number = 0
    //       let stockErr = false
    //       goodsStock.forEach(item => {
    //         if (item.stockPrice !== null && item.stockPrice !== undefined) {
    //           if (item.stockPrice < minPrice) {
    //             minPrice = item.stockPrice
    //           }
    //         }
    //         if (!stockErr) {
    //           stockErr = !item.stockName || item.stockPrice === null || item.stockPrice === undefined || item.stockNum === null || item.stockNum === undefined
    //         }
    //         inventory += (item.stockNum || 0)
    //       })
    //       if (stockErr) {
    //         message.error('请完善商品规格信息')
    //         return Promise.reject()
    //       }
    //       const _saveParams: Parameters<typeof saveGoods>[0] = {
    //         goodsCategory: values.goodsCategory,
    //         goodsDesc: values.goodsDesc,
    //         goodsDetail: JSON.stringify(values.goodsDetail),
    //         goodsId: values.goodsId,
    //         goodsLinePrice: values.goodsLinePrice || 0,
    //         goodsName: values.goodsName,
    //         goodsNum: goodsStock.length > 0 ? inventory : values.goodsNum,
    //         goodsOrder: values.goodsOrder,
    //         goodsPrice: goodsStock.length > 0 ? minPrice : values.goodsPrice,
    //         goodsShow: values.goodsShow,
    //         goodsType: values.goodsType,
    //         logisticsType: values.logisticsInfo.logisticsType,
    //         logisticsPrice: values.logisticsInfo.logisticsPrice,
    //         logisticsId: values.logisticsInfo.logisticsId,
    //         goodsStock: goodsStock.map(it => ({...it, stockSku: (it.stockSku as string[]).join('-')})),
    //         deliver: values.deliver.at(-1),
    //       }
    //       return Promise.resolve(_saveParams)
    //     }).then(params => {
    //     return saveReq.runAsync(params)
    //   }).then(() => {
    //     message.success('保存成功')
    //     cancel()
    //   }).catch(console.log)
    //     .finally(() => {
    //       setSaveLoading(false)
    //     })
    // } else {
    // 需要先保存规格信息
    saveSku()
    .then((res) => {  // 用保存后获取到的真实 sku 替换 fakeId
      const _realSku: Record<string, {realSku: string, img?: string}> = {}
      res.data.forEach(_class => {
        _class.values.forEach(_sku => {
          _realSku[_sku.fakeId!] = {
            realSku: _sku.valueId!,
            img: _sku.valueDesc,
          }
        })
      })

      goodsStock.forEach(item => {
        const _stockSku: string[] = [];
        let _stockImg: string = '';
        (item.stockSku as string[]).forEach(sku => {
          _stockSku.push(_realSku[sku].realSku)
          if (!_stockImg && _realSku[sku].img) {
            _stockImg = _realSku[sku].img!
          }
        })
        item.stockSku = _stockSku
        item.stockImg = _stockImg
      })
      return Promise.resolve()
    })
    .then(() => basicInfoForm.validateFields())
    .then((values: any) => {
      if (goodsStock.length < 1) {
        message.error('请添加商品规格')
        return Promise.reject()
        // if (!values.goodsPrice) {
        //   message.error('请填写价格')
        //   return Promise.reject()
        // }
      }
      let minPrice: number = 1000000
      let inventory: number = 0
      let stockErr = false
      goodsStock.forEach(item => {
        if (item.stockPrice !== null && item.stockPrice !== undefined) {
          if (item.stockPrice < minPrice) {
            minPrice = item.stockPrice
          }
        }
        if (!stockErr) {
          stockErr = !item.stockName || item.stockPrice === null || item.stockPrice === undefined || item.stockNum === null || item.stockNum === undefined
        }
        inventory += (item.stockNum || 0)
      })
      if (stockErr) {
        message.error('请完善商品规格信息')
        return Promise.reject()
      }
      const _saveParams: Parameters<typeof saveGoods>[0] = {
        goodsCategory: values.goodsCategory,
        goodsDesc: values.goodsDesc,
        goodsDetail: JSON.stringify(values.goodsDetail),
        goodsId: values.goodsId,
        goodsLinePrice: values.goodsLinePrice || 0,
        goodsName: values.goodsName,
        goodsNum: inventory,
        goodsOrder: values.goodsOrder,
        goodsPrice: minPrice,
        goodsShow: values.goodsShow,
        goodsType: values.goodsType,
        logisticsType: values.logisticsInfo.logisticsType,
        logisticsPrice: values.logisticsInfo.logisticsPrice,
        logisticsId: values.logisticsInfo.logisticsId,
        goodsStock: goodsStock.map(it => ({...it, stockSku: (it.stockSku as string[]).join('-')})),
        deliver: values.deliver.at(-1),
      }
      return Promise.resolve(_saveParams)
    }).then(params => {
      return saveReq.runAsync(params)
    }).then(() => {
      message.success('保存成功')
      cancel()
    }).catch(console.log)
    .finally(() => {
      setSaveLoading(false)
    })
    // }
  }

  useEffect(() => {
    setSkuList([])
    setGoodsStock([])
    console.log('params', props.params)
    if (props.params.id) {
      goodsDetail
        .runAsync({id: props.params.id})
        .then(res => {
          basicInfoForm.setFieldsValue({
            goodsCategory: String(res.data.goodsCategory),
            goodsDesc: res.data.goodsDesc,
            goodsDetail: JSON.parse(res.data.goodsDetail),
            goodsId: res.data.goodsId,
            goodsLinePrice: res.data.goodsLinePrice,
            goodsName: res.data.goodsName,
            goodsNum: res.data.goodsNum,
            goodsOrder: res.data.goodsOrder,
            goodsPrice: res.data.goodsPrice,
            goodsShow: JSON.parse(res.data.goodsShow).map((it: any) => ({...it, id: it.source})),
            goodsType: res.data.goodsType,
            logisticsInfo: {
              logisticsType: res.data.logisticsType,
              logisticsPrice: res.data.logisticsPrice,
              logisticsId: res.data.logisticsId,
            },
            deliver: [`${res.data.deliver.substring(0, 2)}0000`, `${res.data.deliver.substring(0, 4)}00`, res.data.deliver],
          })
          setSkuList(res.data.goodsSkus.map((it, idx) => {
            if (idx < 1 && it.skuValue?.some(s => s.valueDesc)) {
              return {...it, id: it.classId!, _img: true, values: it.skuValue!.map(item => ({...item, id: item.valueId!, fakeId: item.valueId!}))}
            }
            return {...it, id: it.classId!, values: it.skuValue!.map(item => ({...item, id: item.valueId!, fakeId: item.valueId!}))}
          }))
          setGoodsStock(res.data.goodsStocks.map(it => ({
            ...it, 
            id: it.stockId!, 
            stockSku: (it.stockSku as string).split('-'),
            skuName: getSkuName(it.stockSku as string, res.data.goodsSkus),
          })))
        })
    }
  }, [props.params])

  return (
    <Spin spinning={goodsDetail.loading}>
      <Form form={basicInfoForm} name='addGoodsBasicInfoForm' labelCol={{flex: '100px'}} initialValues={{
        logisticsInfo: {logisticsType: LogisticsType.物流模版},
        goodsOrder: 1,
        goodsType: GoodsType.基础商城,
      }}>
        <Form.Item name='goodsId' noStyle><Input hidden /></Form.Item>
        <Form.Item name='goodsOrder' noStyle><InputNumber style={{display: 'none'}} /></Form.Item>
        <Form.Item name='goodsType' noStyle><Input hidden /></Form.Item>
        <div className="flex flex-col h-full">
          <div className="grow flex flex-col gap-4 overflow-y-auto">
            <Card header='基本信息' className="shrink-0">
              <BasicInfo />
            </Card>
            <Card header='价格和库存' className="shrink-0">
              <div className="flex shrink-0">
                <div className="w-[100px] lh-8 text-right">商品规格：</div>
                <div className="grow">
                  <GoodsSkuInfo />
                </div>
              </div>
              <div className="flex shrink-0 mt-6">
                <div className="w-[100px] lh-8 text-right">规格明细：</div>
                <div className="grow rounded-lg p-2" style={{background: '#f8f8f8'}}>
                  <Inventory value={goodsStock} onChange={setGoodsStock} />
                </div>
              </div>
              {/*<Form.Item v-if hidden={skuList && skuList.length > 0} label='价格' name='goodsPrice' style={{marginTop: 24}}>*/}
              {/*  <InputNumber placeholder="请输入" min={0} precision={2} controls={false} style={{width: 320}}/>*/}
              {/*</Form.Item>*/}
              <Form.Item label='划线价' name='goodsLinePrice' style={{marginTop: 24}}>
                <InputNumber placeholder="请输入" min={0} precision={2} controls={false} style={{width: 320}} />
              </Form.Item>
              {/*<Form.Item v-if hidden={skuList && skuList.length > 0} label='库存' name='goodsNum' style={{marginTop: 24}}>*/}
              {/*  <InputNumber placeholder="请输入" min={0} precision={0} controls={false} style={{width: 320}}/>*/}
              {/*</Form.Item>*/}
            </Card>
            <Card header='物流信息' className="shrink-0">
              <Logistics />
            </Card>
          </div>
          <div className="shrink-0 flex h-16 items-center justify-center gap-4 border-t bg-white" style={{borderColor: 'var(--ant-color-split)'}}>
            <Button type="primary" onClick={submit} loading={saveLoading}>保存</Button>
            <Button onClick={cancel}>取消</Button>
          </div>
        </div>
      </Form>
    </Spin>
  )
}

export default GoodsAdd
